<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { DictApi, ToolTypeApi } from '#/api';

import { reactive, ref } from 'vue';

import { VxeButton, VxeModal } from '@vben/plugins/vxe-table';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictResp, tmToolTypeList } from '#/api';
import { getToolBarBtns, PopMsg, setToolBarBtnDefaultDisabled } from '#/utils/';

import ToolTypeForm from './modules/form.vue';

// 将字典数据添加到数组中
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
const mes_mainten_type = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no', 'mes_mainten_type']).then((res) => {
  // 将两个数组合并
  if (res.mes_mainten_type) {
    mes_mainten_type.push(...res.mes_mainten_type);
  }
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});

// 存储选中行的响应式变量
const selectedRows = ref<ToolTypeApi.Row[]>([]);
const initData = {
  toolTypeId: null,
  toolTypeCode: '',
  toolTypeName: '',
  codeFlag: 'Y',
  maintenType: null,
  maintenPeriod: null,
  remark: '',
};
selectedRows.value = [initData];

interface RowType {
  toolTypeId: number;
  toolTypeCode: string;
  toolTypeName: string;
  codeFlag: string;
  maintenType: string;
  maintenPeriod: string;
  remark: string;
}

// 查询表单
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入类型编码',
      },
      // defaultValue: '1',
      fieldName: 'toolTypeCode',
      label: '类型编码',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入类型名称',
      },
      fieldName: 'toolTypeName',
      label: '类型名称',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: mes_mainten_type,
        placeholder: '请选择',
      },
      fieldName: 'maintenType',
      label: '保养维护类型',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

// 表格左上角按钮
const buttons = getToolBarBtns();
// 表格配置
const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    // { title: '序号', type: 'seq', width: 50 },
    { field: 'toolTypeId', align: 'left', type: 'checkbox', width: 50 },
    {
      field: 'toolTypeCode',
      title: '类型编码',
      cellRender: { name: 'CellButtonInfo', props: { onClick: onEdit } },
    },
    { field: 'toolTypeName', title: '类型名称' },
    {
      field: 'codeFlag',
      title: '是否编码管理',
      cellRender: { name: 'CellTag' },
    },
    {
      field: 'maintenType',
      title: '保养维护类型',
      formatter: ({ cellValue }) => {
        const item = mes_mainten_type.find((item) => item.value === cellValue);
        return item?.label || '无';
      },
    },
    {
      field: 'maintenPeriod',
      title: '保养周期',
      formatter: ({ cellValue, row }) => {
        if (row.maintenType === 'REGULAR') {
          return `${cellValue}天`;
        } else if (row.maintenType === 'USAGE') {
          return `${cellValue}次`;
        } else {
          return '无';
        }
      },
    },
    {
      field: 'remark',
      title: '备注',
      formatter: ({ cellValue }) => {
        return cellValue || '-';
      },
    },
    { field: 'action', title: '操作', slots: { default: 'action' } },
  ],
  keepSource: true,
  pagerConfig: {
    enabled: true,
    // 每页显示数量选择
    pageSizes: [10, 20, 50, 100],
    // 分页布局
    layouts: [
      'Sizes',
      'Total',
      'PrevJump',
      'PrevPage',
      'Number',
      'NextPage',
      'NextJump',
      'FullJump',
    ],
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const resp = await tmToolTypeList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        return { total: resp.total, items: resp.rows };
      },
    },
  },
  toolbarConfig: {
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    refresh: true,
    buttons: buttons.value,
  },
};

// 控制modal的响应式变量
const showPopup = ref(false);

/**
 * 编辑
 * @param row
 */
function onEdit(row: ToolTypeApi.Row) {
  selectedRows.value = [row];
  showPopup.value = true;
}

/**
 * 创建
 */
function onAdd() {
  selectedRows.value = [initData];
  showPopup.value = true;
}

/**
 * 删除
 * @param row
 */
function onDelete(row: ToolTypeApi.Row | ToolTypeApi.Row[]) {
  console.warn(row);
  refreshGrid();
}

// 表格事件
const gridEvents: VxeGridListeners = {
  toolbarButtonClick({ code }) {
    // console.warn(code);
    switch (code) {
      case 'myAdd': {
        // 新增逻辑
        onAdd();
        break;
      }
      case 'myDel': {
        // 删除逻辑
        console.warn('删除选中行:', selectedRows.value);
        onDelete(selectedRows.value);
        break;
      }
      case 'mySave': {
        // 修改逻辑
        if (selectedRows.value.length > 1) {
          PopMsg('请选择单行', '提示', 'error');
        } else {
          onEdit(selectedRows.value[0] as any);
        }
        break;
      }
      default: {
        break;
      }
    }
  },
  checkboxChange({ records }) {
    // const selectedIds = records.map((record) => record.toolTypeId);
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
  checkboxAll({ records }) {
    // const selectedIds = records.map((record) => record.toolTypeId);
    // console.warn('All selected IDs:', selectedIds);
    selectedRows.value = records;
    setToolBarBtnDefaultDisabled(buttons, records.length);
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});
// console.warn(gridEvents);

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
function removeRow(row: RowType) {
  console.warn(row);
}
function editRow(row: ToolTypeApi.Row) {
  onEdit(row);
}

const confirmEvent = () => {
  message.success('点击确认');
  console.warn(selectedRows.value[0]);
  selectedRows.value = [initData];
};

const cancelEvent = () => {
  message.success('点击取消');
  selectedRows.value = [initData];
};

// const data = reactive<ToolTypeApi.Row | {}>({});
</script>

<template>
  <div class="vp-raw w-full">
    <Grid>
      <template #action="{ row }">
        <VxeButton
          mode="text"
          status="primary"
          icon="vxe-icon-signature"
          @click="editRow(row)"
        >
          修改
        </VxeButton>
        <VxeButton
          mode="text"
          status="error"
          icon="vxe-icon-delete"
          @click="removeRow(row)"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
    <!-- <VxeButton content="点击弹出" @click="showPopup = true" /> -->
    <VxeModal
      show-footer
      show-confirm-button
      show-cancel-button
      v-model="showPopup"
      v-if="showPopup"
      width="70%"
      height="40%"
      @confirm="confirmEvent"
      @cancel="cancelEvent"
      @close="cancelEvent"
    >
      <ToolTypeForm
        v-model:data="selectedRows[0]"
        v-model:yes-no="sys_yes_no"
        v-model:mainten-type="mes_mainten_type"
      />
    </VxeModal>
  </div>
</template>
